﻿using BaseUtils;
using BaseUtils.Logger;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using Service.src.Flow.JavaScript;
using Service.src.NW.Model;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Service.src
{
    public class WebView2Handler
    {

        public static bool Env = BaseService.AppConfig.field.SupplierName == "NWP";
        public static string DefaultUrlDev = "http://localhost:5173/#/project/items";
        public static string DefaultUrlProd = BaseService.AppConfig.field.WindowFile;
        //public static string DefaultUrlProd = "file://" + AppData.AppPath + "dist/index.html#/";
        public string uri;
        public WebView2 View;
        private bool _isInitialized = false; // 标记初始化状态
        public WebView2Handler() { }

        public WebView2Handler(WebView2 _View)
        {
            View = _View;

            // 初始化WebView2环境并配置跨域参数
            //  InitWebView2Environment();

            //var envOptions = new CoreWebView2EnvironmentOptions(
            //    additionalBrowserArguments: "--disable-web-security --allow-file-access-from-files --allow-file-access"
            //);
            //var env = CoreWebView2Environment.CreateAsync(
            //           browserExecutableFolder: null,
            //              options: envOptions).GetAwaiter().GetResult();
            //View.EnsureCoreWebView2Async(env);

  
        }

        /// <summary>
        /// 异步初始化WebView2环境（核心修复）
        /// </summary>
        private async Task InitializeAsync()
        {
            string sdf = "file://" + AppData.AppPath + "dist/index.html#/";
            if (_isInitialized || View.CoreWebView2 != null)
                return;

            try
            {
                // 1. 配置浏览器参数（启用本地文件访问和跨域）
                var envOptions = new CoreWebView2EnvironmentOptions(
                    additionalBrowserArguments: "--disable-web-security --allow-file-access-from-files --allow-file-access --disable-features=WebSecurity"
                );

                // 2. 异步创建环境（指定用户数据目录，避免权限问题）
                var env = await CoreWebView2Environment.CreateAsync(
                    browserExecutableFolder: null,
                    userDataFolder: Path.Combine(AppData.AppPath, "WebView2UserData"), // 关键：独立用户目录
                    options: envOptions
                );

                // 3. 等待CoreWebView2初始化完成
                await View.EnsureCoreWebView2Async(env);

                // 4. 启用虚拟主机映射（替换file://协议）
                string distFolder = Path.Combine(AppData.AppPath, "dist");
                if (Directory.Exists(distFolder))
                {
                    View.CoreWebView2.SetVirtualHostNameToFolderMapping(
                        "appassets.example", // 虚拟域名
                        distFolder,
                        CoreWebView2HostResourceAccessKind.Allow
                    );
                    LoggerService.Info($"虚拟主机映射成功：http://appassets.example -> {distFolder}");
                }
                else
                {
                    LoggerService.Warning($"dist文件夹不存在：{distFolder}，可能导致资源加载失败");
                }

                // 5. 注册资源请求事件（处理CORS和MIME类型）
                View.CoreWebView2.WebResourceRequested += CoreWebView2_WebResourceRequested;

                _isInitialized = true;
                LoggerService.Info("WebView2环境初始化完成");
            }
            catch (Exception ex)
            {
                LoggerService.Error($"WebView2初始化失败：{ex.Message}", ex);
            }
        }

        /// <summary>
        /// 处理Web资源请求，添加跨域响应头
        /// </summary>
        private void CoreWebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
        {
            // 修复1：为JS文件添加正确的MIME类型
            if (e.Request.Uri.EndsWith(".js", StringComparison.OrdinalIgnoreCase))
            {
                AddHeaderIfNotExists(e.Response.Headers, "Content-Type", "application/javascript; charset=utf-8");
            }
            // 修复2：处理CSS文件MIME类型
            else if (e.Request.Uri.EndsWith(".css", StringComparison.OrdinalIgnoreCase))
            {
                AddHeaderIfNotExists(e.Response.Headers, "Content-Type", "text/css; charset=utf-8");
            }

            // 仅处理API请求
            if (e.Request.Uri.StartsWith("http://127.0.0.1") || e.Request.Uri.StartsWith("http://localhost"))
            {
                try
                {
                    // 旧版本WebView2使用GetResponseHeaders()方法
                    CoreWebView2HttpResponseHeaders responseHeaders = e.Response.Headers;

                    // 添加CORS响应头
                    AddHeaderIfNotExists(responseHeaders, "Access-Control-Allow-Origin", "*");
                    AddHeaderIfNotExists(responseHeaders, "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                    AddHeaderIfNotExists(responseHeaders, "Access-Control-Allow-Headers", "*");

                    // 处理预检请求
                    if (e.Request.Method.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase))
                    {
                        // 创建空响应处理OPTIONS请求
                        var emptyResponse = View.CoreWebView2.Environment.CreateWebResourceResponse(
                            null,
                           204,
                           "No Content",
                            "Access-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS\r\nAccess-Control-Allow-Headers: *"
                        );
                        e.Response = emptyResponse;
                    }
                }
                catch (Exception ex)
                {
                    LoggerService.Error($"处理Web资源请求时出错: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 安全添加响应头，避免重复
        /// </summary>
        private void AddHeaderIfNotExists(CoreWebView2HttpResponseHeaders headers, string name, string value)
        {
            if (!headers.Contains(name))
            {
                headers.AppendHeader(name, value);
            }
        }
        /// <summary>
        /// 初始化页面
        /// </summary>
        public void InitWebView2(string URL)
        {
            LoggerService.Info(URL);
            View.Source = new Uri(URL);

            // InitWebView2Environment();
        }

        /// <summary>
        /// 监听页面是否加载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void MainView_NavigationCompleted(
            object sender, CoreWebView2NavigationCompletedEventArgs e,
            WebView2 View2)
        {
            // 检查是否成功加载页面
            if (e.IsSuccess)
            {          // 异步初始化，避免阻塞UI线程
                InitializeAsync().ConfigureAwait(false);
                LoggerService.Info("页面加载完成");
                string _URL = Env ? GetProdUrl() : WebView2Handler.DefaultUrlDev;
                _URL += uri;
                InitWebView2(_URL);

                Task.Run(async () =>
                {
                    await Task.Delay(1000);
                    AppData.AppRunSuccessed();
                });

                Task.Run(() =>
                {
                    Refresh(View2);
                });
            }
            else
            {
                LoggerService.Info("页面加载失败" + e.WebErrorStatus);
            }
        }

        private string GetProdUrl()
        {
            return WebView2Handler.DefaultUrlProd;
        }

        private void Refresh(WebView2 Page)
        {
            int RefreshTime = BaseService.AppConfig.field.Refresh;

            int RunTime = 1;
            int SleepTime = 60000;
            while (RefreshTime > 0)
            {
                string Url = Page.Source.ToString();
                Thread.Sleep(SleepTime);
                RunTime += SleepTime;
                if (RunTime > RefreshTime && (Url.Contains("chart/preview") || Url.Contains("/flow")))
                {
                    RunTime = 1;
                    JavaScriptEvent.Send(JavaScriptEventEnum.SYSTEM_NOTIFICATION, SystemNotificationEnum.REFRESH_PAGE.ToString());
                    LoggerService.Warning("重载中...");
                }
            }
        }
    }
}
